<template>
  <div class="table-box">
    <ProTable ref="proTable" title="配置列表" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button
            type="primary"
            :icon="CirclePlus"
            @click="openDrawer('新增', {value: ''})"
            v-auth="'/sys/config/add'"
        >新增配置</el-button
        >
        <el-button
            type="danger"
            :icon="Delete"
            plain
            v-auth="'/sys/config/delete/*'"
            @click="batchDeleteValue(scope.selectedListIds)"
            :disabled="!scope.isSelected"
        >
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- sort -->
      <template #sort="scope">
        <el-input-number
            size="small"
            :model-value="scope.row.sort"
            :disabled="!authButton('/sys/config/setSort')"
            @change="(val: number) => changeSort(val, scope.row)"
        />
      </template>
      <!-- status -->
      <template #status="scope">
        <el-switch
            :model-value="scope.row.status"
            active-text="启用"
            inactive-text="禁用"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            :disabled="!authButton('/sys/config/change_status/*')"
            @click="changeStatus(scope.row)"
        />
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button
            type="primary"
            link
            :icon="EditPen"
            v-auth="'/sys/config/edit/*'"
            @click="openDrawer('编辑', scope.row)"
        >编辑</el-button
        >
        <el-button
            type="primary"
            link
            :icon="Delete"
            v-if="scope.row.isAdmin !== 1 && authButton('/sys/config/delete/*')"
            @click="deleteSysConfig(scope.row)"
        >删除</el-button
        >
      </template>
    </ProTable>
    <SysConfigDrawer ref="sysConfigRef" />
    <ImportExcel ref="importRef" />
  </div>
</template>

<script lang="ts">
export default {
  name: "configManage",
}
</script>

<script lang="ts" setup>
import {ref, onBeforeMount, reactive, onMounted} from "vue";
import { config } from "./config.ts";
import { authButton } from "@/hooks/useAuthButton";
import {
  sysConfigTypesApi,
  sysConfigPageListApi,
  changeStatusApi,
  changeSortApi,
  addSysConfigApi,
  editSysConfigApi,
  deleteSysConfigByIdApi,
  deleteSysConfigApi,
  sysConfigFieldTypesApi
} from "@/api/modules/config";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import SysConfigDrawer from "@/views/system/config/ConfigDrawer.vue";
import { Recordable } from "@/interface/types";
import { authTreeApi } from "@/api/modules/auth.ts";
import { deptTreeCacheApi } from "@/api/modules/dept.ts";
import { cateTreeCacheApi } from "@/api/modules/cate.ts";
import {dictListApi} from "@/api/modules/dict.ts";

const configTypes = ref<any[]>([]);
const fieldTypes = ref<any[]>([]);
const { columns } = config(configTypes.value, fieldTypes.value);

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

onBeforeMount(() => {
  getConfigTypes();
  getConfigFieldTypes();
});

const dictList = ref<any[]>([]);
const authTree = ref<any[]>([]);
const deptTree = ref<any[]>([]);
const cateTree = ref<any[]>([]);
onMounted(() => {
  authTreeApi({}).then(res => {
    authTree.value = res.data as any[];
  })
  deptTreeCacheApi().then(res => {
    deptTree.value = res.data as any[];
  })
  cateTreeCacheApi().then(res => {
    cateTree.value = res.data as any[];
  })
  dictListApi({}).then(res => {
    dictList.value = res.data as any[];
  })
})

const getConfigTypes = async () => {
  const res = await sysConfigTypesApi();
  configTypes.value = res.data as any[];
  proTable.value?.updateSearchColumn({ key: "type", data: res.data });
};

const getConfigFieldTypes = async () => {
  const res = await sysConfigFieldTypesApi();
  fieldTypes.value = res.data as any[];
  proTable.value?.updateSearchColumn({ key: "field_type", data: res.data });
}

const getTableList = (params: any) => {
  const newParams = processParams(params);
  return sysConfigPageListApi(newParams);
};

// 处理参数
const processParams = (params: any) => {
  return JSON.parse(JSON.stringify(params));
};

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 删除配置信息
const deleteSysConfig = async (row: Recordable) => {
  await useHandleData(deleteSysConfigByIdApi, row.id, `删除【${row.name}】配置`);
  proTable.value.getTableList();
};

// 批量删除配置信息
const batchDeleteValue = async (ids: string[]) => {
  await useHandleData(deleteSysConfigApi, { ids }, "删除所选配置信息");
  proTable.value.clearSelection();
  proTable.value.getTableList();
};

// 切换状态
const changeStatus = async (row: Recordable) => {
  if (!authButton("/sys/config/change_status/*")) {
    return;
  }
  await useHandleData(changeStatusApi, row.id, `切换【${row.name}】配置状态`);
  proTable.value.getTableList();
};

// 修改配置排序
const changeSort = async (val: number, row: Recordable) => {
  if (!authButton("/sys/config/changeSort")) {
    return;
  }
  await useHandleData(changeSortApi, { id: row.id, sort: val }, `修改【${row.name}】配置排序`);
  proTable.value.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const sysConfigRef = ref();
const openDrawer = (title: string, rowData: Partial<Recordable> = {}) => {
  let params = {
    title,
    rowData: { ...rowData },
    isView: title === "查看",
    configTypes: configTypes.value,
    fieldTypes: fieldTypes.value,
    dictList: dictList.value,
    authTree: authTree.value,
    deptTree: deptTree.value,
    cateTree: cateTree.value,
    api: title === "新增" ? addSysConfigApi : title === "编辑" ? editSysConfigApi : "",
    getTableList: proTable.value.getTableList
  };
  sysConfigRef.value.acceptParams(params);
};
</script>

<style lang="scss" scoped></style>
